#include<iostream>
#include<string>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include"InetAddr.hpp"
#include"Comm.hpp"

void User(std::string proc)
{
    std::cout<<"Usage: "<<proc<<" serverip"<<" serverport"<<std::endl;
}

//serverport serverip
int main(int args,char *argv[])
{
    if(args!=3)
    {
        User(argv[0]);
        exit(0);
    }

    uint16_t serverport=std::stoi(argv[2]);
    std::string serverip=argv[1];

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "create client sockfd error" << std::endl;
        exit(SOCKET_CREAT_ERROR);
    }


    // tcp客户端，不要显示的bind
    // 客户端自己的socket地址，让本地os自主随机选择，尤其是端口号
    // 向目标服务器发起连接请求 ！
    InetAddr server(serverport,serverip);
    if(connect(sockfd,server.Addr(),server.Length())!=0)
    {
        std::cerr << "connect server error" << std::endl;
        exit(SOCKET_CONNECT_ERROR);
    }
    std::cout << "connect " << server.ToString() << " success" << std::endl;

    while(true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line);

        ssize_t n=write(sockfd,line.c_str(),line.size());
        if(n>=0)
        {
            char buffer[1024];
            ssize_t m=read(sockfd,buffer,sizeof(buffer)-1);
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<buffer<<std::endl;
            }
        }
    }
    return 0;
}